package com.example.myframe.base.viewmodel

import com.example.myframe.base.repo.EasyHttpRepoKt
import com.hjq.http.config.IRequestApi
import com.hjq.http.request.GetRequest
import com.a.lib_base.base.viewmodel.BaseOwnerViewModel
import com.a.lib_base.base.viewmodel.MviDispatcherKTX
import com.a.lib_network.bean.HttpData

/**
 * CREATE BY 黄炜强
 * 2022/7/20 17:38
 * Desc:本写法得到KunMinX大佬认可  https://juejin.cn/post/7116526281037987871
 * val vm = ViewModelProvider(this)[VM::class.java]
 *    vm.owner=this
 *    vm.login(
 *    ParamsApi(
 *    "/api/b/checkLogin?password=202cb962ac59075b964b07152d234b70&username=123&",
 *    ""
 *    )
 *    )
 *    class VM : EasyHttpViewModelKt(EasyHttpRepoKt()) {
 *        fun login(api: IRequestApi) {
 *            repo.request<HttpData<EmployeeBean>>(repo.get(owner, api), fail = {}) {
 *                LogUtils.i(it.data.employee.employeeName)
 *            }
 *        }
 *      使用拓展函数
 *   otherSaleOutRepoKt.get<HttpData<OtherSaleOutOrder>>(event.api, fail = {}) {
 *      if (isSuccess(event.result, it))
 *      event.result.data.otherSaleOutOrderList = it.getData().otherSaleOutOrderList
 *      viewModelScope.launch {
 *      sendResult(event)
 *      }
 *  }
 *    }
 * */
open class EasyHttpViewModelKt<Event> : MviDispatcherKTX<Event>() {

    /**
     *@param showLoading kotlin 默认参数，如果不修改可以不填
     * */
    inline fun <reified T> EasyHttpRepoKt.get(
        api: IRequestApi,
        result: HttpData<*>,
        showLoading: Boolean = true,
        crossinline success: ((T) -> Unit)
    ) {
        request<T>(getRequest(owner, api), showLoading, fail = {
            result.isSuccess = false
            result.msg = it.message
        }, success)
    }

    inline fun <reified T> EasyHttpRepoKt.get(
        api: IRequestApi,
        showLoading: Boolean = true,
        crossinline fail: ((Throwable) -> Unit),
        crossinline success: ((T) -> Unit)
    ) {
        request<T>(getRequest(owner, api), showLoading, fail, success)
    }
}